/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import entity.Curso;
import entity.Empresa;
import entity.Usuario;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Rodrigo
 */
@Stateless
public class CursoFacade extends AbstractFacade<Curso> {

    @PersistenceContext(unitName = "Epraxis-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CursoFacade() {
        super(Curso.class);
    }

    public List<Curso> getListaCursoUltimosPublicados() {
        String sql = "SELECT * FROM CURSO ORDER BY FECHA_REGISTRO DESC";
        Query query = em.createNativeQuery(sql, Curso.class);
        return query.getResultList();
    }

    public Curso getCursoUltimoCreado() {
        try {
            String sql = "SELECT * FROM CURSO ORDER BY ID DESC LIMIT 1";
            Query query = em.createNativeQuery(sql, Curso.class);
            return (Curso) query.getSingleResult();
        } catch (Exception e) {
            Logger.getLogger(CursoFacade.class.getName()).log(Level.SEVERE, null, e);
            return null;
        }
    }

    public List<Curso> getListaCursoByEmpresa(Empresa empresa) {
        String sql = "SELECT C.* FROM CURSO C "
                + "INNER JOIN USUARIO_CURSO UC ON UC.CURSO_ID = C.ID "
                + "INNER JOIN USUARIO U ON U.ID = UC.USUARIO_ID "
                + "WHERE U.EMPRESA = " + empresa.getId();

        System.out.println("sql = " + sql);

        Query query = em.createNativeQuery(sql, Curso.class);
        return query.getResultList();
    }

    public List<Curso> getListaCursosAsignadosByUsuario(Usuario usuario) {
        String sql = "SELECT C.* FROM CURSO C INNER JOIN USUARIO_CURSO_ASIGNADO UCA ON UCA.CURSO = C.ID WHERE UCA.USUARIO = " + usuario.getId();
        Query query = em.createNativeQuery(sql, Curso.class);
        return query.getResultList();
    }

}
